package com.example.index.system

import android.app.ActivityManager
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.widget.Toast
import com.example.index.R
import es.dmoral.toasty.Toasty
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_detect_app_use_time.*
import java.lang.reflect.Field
import java.util.concurrent.TimeUnit

class DetectAppUseTimeActivity : AppCompatActivity() {

    val TAG = "DetectAppUseActivity"
    var targetAppPackageName = "com.zhiwang.planet"

    val time = 20

    var appLaunched = false

    var procInfoClassProcessStateField: Field? = null

    var disposable: Disposable? = null

    var timer: AppUsageTimer? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detect_app_use_time)

//        timer.start()


        disposable = Flowable.interval(2, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe {
                Log.i(TAG, "onTick: ----tick----")
            }

        button3.setOnClickListener {
            val pkgName = editText.text.toString()
            if (pkgName.isEmpty()) editText.error = "检测包名不能为空"
            else {
                targetAppPackageName = pkgName
                timer = AppUsageTimer(360000, 2000)
                timer?.start()
            }
        }
    }


    fun isAppLaunched(): Boolean {
        val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningTasks = activityManager.getRunningTasks(18)

//        for (runningAppProcess in runningAppProcesses) {
//            Log.i(TAG, "isAppLaunched: ${runningAppProcess.processName}")
//        }

        runningTasks.forEach {
            Log.i(TAG, "isAppLaunched: ${it.topActivity?.packageName}")
        }

        val runningTask = runningTasks[0]

        return runningTask.topActivity?.packageName == targetAppPackageName
    }

//    private fun getProcState(it: ActivityManager.RunningAppProcessInfo?): Int {
//        if (procInfoClassProcessStateField == null)
//            procInfoClassProcessStateField = ActivityManager.RunningAppProcessInfo::class.java.getField("processState")
//        return procInfoClassProcessStateField?.getInt(it) ?: 0
//    }


    inner class AppUsageTimer : CountDownTimer {

        constructor(millisInFuture: Long, countDownInterval: Long) : super(millisInFuture, countDownInterval)


        override fun onFinish() {

        }


        //TODO
        override fun onTick(millisUntilFinished: Long) {
            Log.i(TAG, "onTick: ----tick----")
//            if (isAppLaunched() && appLaunched.not()) {
//                //app 已经启动
//                appLaunched = true
//                Toasty.info(this@DetectAppUseTimeActivity, "App启动！！！", Toast.LENGTH_SHORT).show()
//
//            } else {
//                //app 退回后台
//                if (appLaunched) {
//                    appLaunched = false
//                    Toasty.info(this@DetectAppUseTimeActivity, "App使用时间不够，任务无法完成", Toast.LENGTH_SHORT).show()
//                }
//            }
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
        disposable?.dispose()
    }
}
